<template>
    <div class="mod-config">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
        <el-form-item>
          <el-select 
          v-model="searchBy" 
          clearable 
          placeholder="请选择索引方式"
          @change="search()"
        >
          <el-option
            v-for="item in searchOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        </el-form-item>
        <el-form-item>
        <el-input 
          v-model="searchQuery" 
          :placeholder="getPlaceholder()"
          clearable
        />
      </el-form-item>
        <template>
        <el-form-item label="日期:">
          <el-date-picker
            v-model="dataForm.examTimeRange"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['12:00:00']"
            style="width: ">
           </el-date-picker>
        </el-form-item>
      </template>
        <el-form-item>
          <el-button @click="search()" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        :summary-method="getSummaries"
        show-summary
        style="width: 100%;"
        :row-class-name="tableRowClassName">
        <el-table-column type="index" header-align="center" align="center" label="序号" width="100" />
        <el-table-column prop="deviceId" header-align="center" align="center"  label="设备编号"></el-table-column>
        <el-table-column prop="deviceName" header-align="center" align="center"  label="设备名称"></el-table-column>
        <el-table-column prop="date" header-align="center" align="center" label="日期" :formatter="formatDate"></el-table-column>
        <el-table-column prop="efficiency" header-align="center" align="center"  label="当天效率"></el-table-column>
        
        
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100,500,1000]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </template>
  
  <script>
    export default {//声明模块所需要的变量/函数
      data () {
        return {
          dataForm: {
          deviceId: '',
          deviceName: '',
          examTimeRange:[]
        },
          
          dataList: [],
          pageIndex: 1,
          pageSize: 10,
          totalPage: 0,
          dataListLoading: false,
          searchOptions: [
        { value: 'name', label: '设备名称' },
        { value: 'deviceId', label: '设备编号' }
      ],  
      searchBy: 'name',
      searchQuery: '',
        }
      },
      activated () {//页面激活后调用这个钩子函数
        this.getDataList()
      },
      methods: {
        getPlaceholder() {
      return this.searchBy === 'name' ? '请输入设备名称' : '请输入设备编号';
    },
        tableRowClassName({row, rowIndex}) {
          const remainder = rowIndex % 4;
            if (remainder === 0) return 'warning-row';  // 第1行（索引0）
            if (remainder === 2) return 'success-row';  // 第3行（索引2）
            return '';  // 第2行（索引1）无颜色
        
      },
        // 新增日期格式化方法
    formatDate(row, column) {
      if (row.date) {
        // // 方法1：使用 toISOString 截取前10位
        // return new Date(row.date).toISOString().slice(0, 10);
        
        // 方法2：手动拼接年月日（更兼容）
        const date = new Date(row.date);
        return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
          .map(num => num.toString().padStart(2, '0'))
          .join('-');
      }
      
    },
    getSummaries(param) {
  const { columns, data } = param;
  const sums = new Array(columns.length).fill('');
  columns.forEach((column, index) => {
    // 处理前三列合并显示
    if (index < 3) { 
      sums[0] = '累计效率:';
      sums[1] = 'N/A';
      sums[2] = 'N/A';
      sums[3] = 'N/A';
      return;
    }
    // 处理产量列总计
    if (column.property === 'efficiency') { 
      const values = data.map(item => Number(item[column.property]));
      if (!values.every(value => isNaN(value))) {
        const total = values.reduce((prev, curr) => {
          const num = Number(curr);
          return isNaN(num) ? prev : prev + num;
        }, 0);
        sums[index] = ` ${total}`;
      } else {
        sums[index] = 'N/A';
      }
    }
  });
  return sums;
},
    
        // 查询
        search() {//与点击事件进行绑定，点击查询，页码变为1，并调用获取数据列表函数
          this.pageIndex = 1
          this.getDataList()
        },
        // 获取数据列表
        getDataList () {
          console.log(1111);
          let params ={
            page: this.pageIndex,
              limit: this.pageSize,
              [this.searchBy]: this.searchQuery
          };
          if (Array.isArray(this.dataForm.examTimeRange) && this.dataForm.examTimeRange.length === 2) {
           params.startTime = this.dataForm.examTimeRange[0].getTime();
           params.endTime = this.dataForm.examTimeRange[1].getTime();
            }
          this.dataListLoading = false
          this.$http({
            url: this.$http.adornUrl('/dss/usage/list'),
            method: 'get',
            params: this.$http.adornParams(
              params
            )
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataList = data.page.list
              this.totalPage = data.page.totalCount
            } else {
              this.dataList = []
              this.totalPage = 0
            }
            this.dataListLoading = false
          })
        },
        // 每页数
        sizeChangeHandle (val) {
          this.pageSize = val
          this.pageIndex = 1
          this.getDataList()
        },
        // 当前页
        currentChangeHandle (val) {
          this.pageIndex = val
          this.getDataList()
        },
      }
    }
  </script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>